#include "common.h"
#include <amdev.h>

size_t serial_write(const void *buf, size_t offset, size_t len) {
  _yield();
  char* str = (char*)buf;
  for (size_t i = 0; i < len; i++) {
    _putc(str[i]);
  }
  return len;
}

#define NAME(key) \
  [_KEY_##key] = #key,

static const char *keyname[256] __attribute__((used)) = {
  [_KEY_NONE] = "NONE",
  _KEYS(NAME)
};

size_t events_read(void *buf, size_t offset, size_t len) {
  _yield();
  int key = read_key();
  int down = 0;
  uint32_t msec;
  if (key & 0x8000) {
    key ^= 0x8000;
    down = 1;
  }
  if (key != _KEY_NONE) {
    if(down){
      // sprintf(buf,"kd %s / ku %s\n\0", down ? keyname[key] : keyname[0], keyname[key]);
      sprintf(buf,"kd %s\n\0", keyname[key]);
    }else {
      sprintf(buf,"ku %s\n\0", keyname[key]);
    }
    return strlen(buf);
  }
  msec = uptime();
  sprintf(buf,"t %d\n\0", msec);
  // printk("events read %d buf : %s",msec,buf);
  return strlen(buf);
}

static char dispinfo[128] __attribute__((used)) = {};

size_t dispinfo_read(void *buf, size_t offset, size_t len) {

  char* str = (char*)buf;
  // size_t displen = strlen(dispinfo);

  char* curInfo = dispinfo + offset;

  memcpy((uint32_t *)buf , curInfo, strlen(curInfo));
  str[strlen(curInfo)]='\0';

  return strlen(str);
}

int screen_wid;
int screen_hig;


size_t fb_write(const void *buf, size_t offset, size_t len) {
  _yield();
  // int h = offset / screen_width();
  // int w = offset - h*screen_width();
  // printf("start fb write offset=%d h=%d,w=%d len =%d\n",offset,h,w,len);
  offset /= sizeof(uint32_t);
  int y = offset / screen_wid;
  int x = offset - y*screen_wid;
  draw_rect((uint32_t *)buf, x, y, len/sizeof(uint32_t), 1);
  // uint32_t* fb = (uint32_t*)0xa0000000;
  // memcpy(fb + offset/screen_height(),buf,len);
  return len;
}

size_t fbsync_write(const void *buf, size_t offset, size_t len) {
  draw_sync();
  return len;
}

void init_device() {
  Log("Initializing devices...");
  _ioe_init();

  // TODO: print the string to array `dispinfo` with the format
  // described in the Navy-apps convention
  screen_wid = screen_width();
  screen_hig = screen_height();
  memset(dispinfo,0,128);
  sprintf(dispinfo,"WIDTH:%d\nHEIGHT:%d\n",screen_wid,screen_hig);
                            //HEIGHT
}
